﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Linq;

namespace CommonModel
{
    public class Tree<T> where T : class
    {
        public List<TreeNode<T>> Nodes { get; set; }

        public string ToJson()
        {
            return "[" + string.Join(",", Nodes.Select(n => n.ToJson())) + "]";
        }

    }
    public class TreeNode<T> where T : class
    {
        public TreeNode()
        {
            Children = new List<TreeNode<T>>();
        }
        public TreeNode(T value)
        {
            NodeValue = value;
            Children = new List<TreeNode<T>>();
        }
        public TreeNode<T> ParentNode { get; set; }
        public T NodeValue { get; set; }
        /// <summary>
        /// 返回children 禁止直接 Children.Add()
        /// </summary>
        public List<TreeNode<T>> Children
        {
            get;
            private set;
        }
        /// <summary>
        /// 返回Children
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public TreeNode<T> AddChildren(T value)
        {
            TreeNode<T> n = new TreeNode<T>(value);
            n.ParentNode = this;
            this.Children.Add(n);
            return n;
        }
        /// <summary>
        /// 添加并返回Children
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public TreeNode<T> AddChildren(TreeNode<T> t)
        {
            t.ParentNode = this;
            this.Children.Add(t);
            return t;
        }

        /// <summary>
        /// 生成easyui  tree 和treegrid 数据
        /// </summary>
        /// <returns></returns>
        public string ToJson()
        {

            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            if (Children == null || Children.Count == 0) { return JsonConvert.SerializeObject(NodeValue, timeFormat); }
            return JsonConvert.SerializeObject(NodeValue, timeFormat).TrimEnd('}') + ",children:[" + string.Join(",", Children.Select(n => n.ToJson())) + "]}";
        }
    }
}
